package com.ccloud.common.minio.properties;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.SetBucketPolicyArgs;
import io.minio.errors.*;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author chentl
 * @date 2021/10/28
 */

@Data
@Configuration
public class MinioProperties {

    /**
     * minio的url和端口
     **/
    public static String endpoint;

    /**
     * minio的accessKey
     **/
    public static String accessKey;

    /**
     * minio的secretKey
     **/
    public static String secretKey;

    /**
     * minio BucketName
     */
    public static String bucketName;


    @Value("${minio.endpoint:http://192.168.31.236:19000/}")
    public void setEndpoint(String endpoint) {
        MinioProperties.endpoint = endpoint;
    }

    @Value("${minio.accessKey:minioadmin}")
    public void setAccessKey(String accessKey) {
        MinioProperties.accessKey = accessKey;
    }

    @Value("${minio.secretKey:minioadmin}")
    public void setSecretKey(String secretKey) {
        MinioProperties.secretKey = secretKey;
    }

    @Value("${minio.bucketName:shenfeng-motor-factory}")
    public void setBucketName(String bucketName) {
        MinioProperties.bucketName = bucketName;
    }

    /**
     * 初始化 MinIO 客户端
     */
    @Bean
    public MinioClient minioClient() throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, ErrorResponseException {
        String endpoint = MinioProperties.endpoint;
        String accessKey = MinioProperties.accessKey;
        String secretKey = MinioProperties.secretKey;
        String bucketName = MinioProperties.bucketName;
        MinioClient minioClient = MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();

        boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (!isExist) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
            String policyJson = "Bucket already exists.";
            minioClient.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(bucketName).config(policyJson).build());
        }

        return minioClient;
    }

}
